package Advanced.stickyPacks;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class stickyPacksServer {

    public static NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);

    public static NioEventLoopGroup workerGroup = new NioEventLoopGroup(2);

    public static void main(String[] args) throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup);
        serverBootstrap.channel(NioServerSocketChannel.class);
        Channel channel = serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                //会记录通过通道发送和接收的数据
                pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
                pipeline.addLast(new ChannelInboundHandlerAdapter(){

                    // 连接
                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        log.debug("connected {}", ctx.channel());
                        super.channelActive(ctx);
                    }

                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        super.channelRead(ctx, msg);
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                        log.debug("disconnect {}", ctx.channel());
                        super.channelInactive(ctx);
                    }
                });
            }
        }).bind(8080).sync().channel();
    }
}
